<template>
  <el-button
@click="handleAdd({id: 0,name:'',parentId:0,level:0,items:[],hasChildren:false})" v-if="$filters.auth($filters.PrivilegeType.Add)" class="button-header"  type="primary" :icon="Plus">新增地区</el-button>
  <el-table ref="cTable" :data="list" style="width: 100%; margin-bottom: 20px" row-key="id" border default-expand-all :tree-props="{ children: 'items', hasChildren: 'hasChildren' }" lazy :load="load">
    <el-table-column prop="name" label="名称" />
    <el-table-column label="操作" align="right" width="220">
      <template #default="scope">
        <el-button type="text" v-if="scope.row.level < 4 && $filters.auth($filters.PrivilegeType.Add)" @click.stop="handleAdd(scope.row)">新增下级分类</el-button>
        <el-button type="text" v-if="$filters.auth($filters.PrivilegeType.Edit)" @click="handleEdit(scope.row)">编辑</el-button>
        <el-popconfirm v-if=" $filters.auth($filters.PrivilegeType.Delete)" class="btn-popconfirm" @confirm="handleDelete(scope.row)" confirmButtonText="确认" cancelButtonText="取消" title="确定要删除该分类吗？">
          <template #reference>
            <el-button type="text" size="small">删除</el-button>
          </template>
        </el-popconfirm>
      </template>
    </el-table-column>
  </el-table>
  <!--添加编辑-->
  <el-dialog append-to-body v-model="dialogVisible" :title="title" width="550px">
    <el-form ref="postForm" label-width="150px" class="ruleForm" :model="form" :rules="rules">
      <el-form-item label="地区名称：" prop="name">
        <el-col :span="22">
          <el-input v-model="form.name" maxlength="20" show-word-limit placeholder="请输入地区名称" />
        </el-col>
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSave(postForm)">确定</el-button>
      </span>
    </template>
  </el-dialog>
  <!--添加编辑 end-->
</template>
<script lang="ts" setup>
  import { Plus } from '@element-plus/icons-vue'
  import { ref, reactive, onMounted } from 'vue'
  import { AreaSubs, AreaCreate, AreaSave, AreaDelete } from '@/api/area'
  import { ElForm, ElMessage, ElTable } from 'element-plus'

    type FormInstance = InstanceType<typeof ElForm>
    const postForm = ref<FormInstance>()
    const cTable =ref<any>()
    let tableRow :RegionData = {
      id: 0,
      name:'',
      parentId:0,
      level:0,
      items:[],
      hasChildren:false
    }

    const form = reactive({
      id: 0,
      name:'',
      parentId:0,
    })
    const rules = reactive({
      name: [{ required: true, message: '请输入地区名称', trigger: 'blur' }]
    })
    /** 弹窗 */
    const dialogVisible = ref<boolean>(false)
    const title = ref<string>('添加地区')
    const list = ref<RegionData[]>([])
    /**加载数据 */
    const loadData = (): void => {
      AreaSubs(0).then((res: ServiceResponse<RegionData[]>) => {
        if (res.success) {
          list.value = res.data ?? []
        }
      })
    }
    /** 加载子节点 */
    const load = (row: RegionData, treeNode: any, resolve: any): void => {
      AreaSubs(row.id).then((res: ServiceResponse<RegionData[]>) => {
        if (res.success) {
          resolve(res.data ?? [])
        }
      })
    }
    /** 添加 */
    const handleAdd = (region: RegionData): void => {
      form.id = 0
      form.name = ''
      form.parentId = region.parentId
      dialogVisible.value = true
      title.value ='添加地区'
      tableRow = region
    }
    /** 编辑 */
    const handleEdit = (region: RegionData): void => {
      form.id = region.id,
      form.name = region.name,
      form.parentId = 0,
      dialogVisible.value = true
      title.value ='编辑地区'
      tableRow = region
    }
    /** 删除 */
    const handleDelete = (region: RegionData): void => {
      AreaDelete(region.id).then((res: ServiceResponse<boolean>) => {
        if (res.success) {
          ElMessage.success('删除成功')
          refreshTable()
        } else  ElMessage.error(res.msg)
      })
    }
    /** 保存 */
    const handleSave  = (formEl: FormInstance | undefined): void => {
      if (!formEl) return
      formEl.validate((valid) => {
        if (valid) {
          if(form.id === 0) {
            AreaCreate(form.name,form.parentId).then((res:ServiceResponse<any>)=>{
              if (res.success) {
                  dialogVisible.value = false
                  ElMessage.success('操作成功')
                  refreshTable()
              } else  return ElMessage.error(res.msg)
            })
          } else {
            AreaSave(form.id,form.name).then((res:ServiceResponse<any>)=>{
              if (res.success) {
                  dialogVisible.value = false
                  ElMessage.success('操作成功')
                  refreshTable()
              } else   return ElMessage.error(res.msg)
            })
          }
        }
      })
    }
    const refreshTable = (): void => {
      if(tableRow.parentId === 0)
        loadData()
      else {
        cTable.value.store.states.treeData.value[tableRow.id].loaded = false
        cTable.value.store.loadOrToggle(tableRow)
      }
    }
    onMounted(() => {
      loadData()
    })
</script>

<style lang="scss" scoped>
  @import '@/assets/styles/mixin.scss';
  @import '@/assets/styles/tablePage.scss';
  @import '@/assets/styles/formPage.scss';
</style>